<template>
    <UserLayout>
        <div class="main">
            <van-form @submit="onSubmit">

                <van-cell-group inset>
                    <van-field v-model="loginParams.username" left-icon="user-o" placeholder="请输入用户名丶工号或手机号"
                        custom-style="position: relative;" :rules="[{ required: true, message: '请输入用户名' }]">
                        <template #error-message>
                            <div class="error-message">
                                请输入用户名
                            </div>
                        </template>
                    </van-field>
                </van-cell-group>

                <van-cell-group inset>
                    <van-field v-model="loginParams.password" :type="passwordType" left-icon="birthday-cake-o"
                        placeholder="密码" :rules="[{ required: true, message: '请输入密码' }]">

                        <template #right-icon>
                            <van-icon name="eye" class="eye-icon" @click="switchPasswordType"
                                :class="{ 'van-icon--close': passwordType === 'text' }" />
                        </template>

                        <template #error-message>
                            <div class="error-message">
                                请输入密码
                            </div>
                        </template>
                    </van-field>
                </van-cell-group>

                <div class="checkbox">
                    <van-row>
                        <van-col span="16">
                            <van-cell-group inset style="margin: 0;">
                                <van-field left-icon="smile-o" placeholder="请输入验证码" v-model="loginParams.captcha"
                                    :rules="[{ required: true, message: '请输入验证码' }]">
                                    <template #error-message>
                                        <div class="error-message">
                                            请输入验证码
                                        </div>
                                    </template>
                                </van-field>
                            </van-cell-group>
                        </van-col>
                        <van-col span="8" style="text-align: right">
                            <img v-if="requestCodeSuccess" :src="randCodeImage" @click="handleChangeCheckCode" />
                            <img v-else src="~@/assets/checkcode.png" alt="logo">
                        </van-col>
                    </van-row>
                </div>

                <div class="checkbox">
                    <van-checkbox v-model="loginParams.rememberMe" shape="square">
                        自动登录
                    </van-checkbox>
                </div>

                <div class="submit_btn">
                    <van-button :loading="loginBtn" type="primary" block native-type="submit" size="small">
                        确定
                    </van-button>
                </div>
            </van-form>
        </div>
    </UserLayout>
</template>

<script setup>
import UserLayout from '@/components/layouts/UserLayout.vue'
import { reactive, ref, nextTick } from 'vue'
import { getAction } from '@/api/manage'
import { login, wxAuthlogin } from '@/api/login'
import { getUrlParam } from '@/utils/hooks/checkDate'
import { useRouter } from "vue-router"
import userStore from "@/stores/modules/user"
import { showToast, showNotify } from 'vant'
import { timeFix } from '@/utils/util'

import 'vant/es/toast/style'
import 'vant/es/notify/style'

const user = userStore()
const router = useRouter()
let passwordType = ref('password')
let wxLoging = ref(false)
let loginBtn = ref(false)
let requestCodeSuccess = ref(false) //控制验证码图片
let currdatetime = ref('')
let randCodeImage = ref('') //验证码图片
let redirect = reactive({})

//获取验证码
const handleChangeCheckCode = () => {
    currdatetime = new Date().getTime()
    getAction(`/sys/randomImage/${currdatetime}`)
        .then(res => {
            if (res.success) {
                randCodeImage.value = res.result
                requestCodeSuccess.value = true
            } else {
                //缺少错误提示
                requestCodeSuccess.value = false
            }
        })
        .catch(() => {
            requestCodeSuccess.value = false
        })
}

const getRouterData = () => {
    nextTick(() => {
        if (redirect.username) {
            //   form.setFieldsValue({
            //     username: this.$route.params.username,
            //   })
        }
    })
}

redirect = decodeURI(router.currentRoute.value.query)
let urlParam = getUrlParam(redirect)
if (urlParam && urlParam.code && urlParam.state) {
    wxLoging.value = true
    let redirectUri = urlParam.retUrl
    user.Login(urlParam, wxAuthlogin).then(res => {
        if (res.success) {
            if (!redirectUri || redirectUri == '/') {
                redirectUri = '/home'
            }
            delete urlParam['retUrl']
            delete urlParam['code']
            delete urlParam['state']
            if (Object.keys(urlParam).length > 0) {
                router.push({ path: redirectUri, query: urlParam })
            } else {
                router.push({ path: redirectUri })
            }
        } else {
            wxLoging.value = false
            wxLoginFailed(res)
        }
    }).catch(err => {
        wxLoging.value = false
        wxLoginFailed(err)
    })
} else {
    currdatetime = new Date().getTime()
    //清除token
    getRouterData() //目前不懂是干嘛的
    handleChangeCheckCode()
}

const wxLoginFailed = (err) => {
    requestFailed(err)
    handleChangeCheckCode()
}


const loginParams = reactive({
    username: '',
    password: '',
    captcha: '',
    rememberMe: true
})

//账号密码登录
const onSubmit = () => {
    loginBtn.value = true
    user.Login(loginParams, login).then(res => {
        departConfirm(res)
    }).catch(err => {
        requestFailed(err)
    })
}

const loginSuccess = () => {
    // update-begin- author:sunjianlei --- date:20190812 --- for: 登录成功后不解除禁用按钮，防止多次点击
    // this.loginBtn = false
    // update-end- author:sunjianlei --- date:20190812 --- for: 登录成功后不解除禁用按钮，防止多次点击
    router.push({ path: '/' })
    showNotify({ type: 'success', message: `${timeFix()}，欢迎回来` })
    //   localStorage.removeItem('invoiceTel')
}

const requestFailed = (err) => {
    showNotify({ type: 'danger', message: ((err.response || {}).data || {}).message || err.message || '请求出现错误，请稍后再试' });
    loginBtn.value = false
}

const departConfirm = res => {
    if (res.success) {
        let multi_depart = res.result.multi_depart
        //0:无部门 1:一个部门 2:多个部门
        if (multi_depart == 0) {
            //   this.loginSuccess()
            showToast({
                message: '您尚未归属部门,请确认账号信息',
                position: 'top',
            });
        } else {
            loginSuccess()
        }
    } else {
        requestFailed(res)
        user.Logout()
    }
}

const switchPasswordType = () => {
    passwordType.value = passwordType.value === 'password' ? 'text' : 'password';
}
</script>

<style lang="scss" scoped>
:deep(.van-checkbox__icon) {
    font-size: $checkbox_size;
}

:deep(.van-cell-group--inset),
.checkbox,
.submit_btn {
    margin: $home_margin_L $home_margin_H;
}

:deep(.van-cell-group--inset) {
    border-radius: 4px;
    overflow: visible;

    .van-cell {
        overflow: visible;

    }
}

.van-cell {
    padding: 6px 10px;
    border: 1px solid #e0e0e0;
}

.checkbox {
    font-size: 14px;

    img {
        width: 100px;
        height: 36px;
    }
}

.error-message {
    position: absolute;
    bottom: -28px;
    z-index: 10000;
}
</style>